package com.xyhy.core.file.oss.aliyun;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.*;
import com.xyhy.core.base.ToolConstant;
import com.xyhy.core.utils.time.LocalDateUtil;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

/**
 * @author robert
 * @since 2024-12-05
 */
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@ApiModel("阿里OSS上传策略")
public class AliUploadPolicy {

  @ApiModelProperty("有效时长，格式为UTC时间")
  private String expiration;

  @Builder.Default
  @ApiModelProperty("设置上传文件的大小限制等条件")
  private List<JSONArray> conditions = new ArrayList<>();


  public static AliUploadPolicy build(LocalDateTime expireDate, long fileMaxSize) {
    return AliUploadPolicy.build(expireDate, 0, fileMaxSize);
  }

  public static AliUploadPolicy build(LocalDateTime expireDate, long fileMinSize, long fileMaxSize) {
    String expiration = LocalDateUtil.formatLocalDateTime(expireDate, ToolConstant.PATTERN.UTC);
    List<JSONArray> conditions = CollUtil.newArrayList();
    conditions.add(new JSONArray().put("content-length-range").put(fileMinSize).put(fileMaxSize));
    return AliUploadPolicy.builder().expiration(expiration).conditions(conditions).build();
  }

  @Override
  public String toString() {
    return JSONUtil.toJsonStr(this);
  }

  public String getBase64() {
    return Base64.getEncoder().encodeToString(this.toString().getBytes(StandardCharsets.UTF_8));
  }

}
